package com.hltx.controller.courier;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.courier.Courier;
import com.hltx.pojo.courier.CourierTraces;
import com.hltx.service.courier.CourierManager;
import com.hltx.util.ResultInfo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/courier")
public class CourierController extends BaseController {
	
	@Resource(name="courierService")
	private CourierManager courierService;
	/**
	 * 订单页  显示（物流）
	 * @param request
	 * @return
	 */
	@RequestMapping("/orderTraces.do")
	@ResponseBody
	public Map< String, Object> orderTraces(HttpServletRequest request){
		Map<String,Object> hashMap = new HashMap<>();
		String orderId = request.getParameter("orderId");
		Map<String, Object> number = getCourierNumber(orderId);
		String courier_number = (String) number.get("courier_number");
		String courier_code = (String) number.get("courier_code");
			if(courier_number != null && courier_code != null ){
			try {
				String tracesByJson = courierService.getOrderTracesByJson(courier_code,courier_number);
				//根据公司业务处理返回的信息......
				JSONObject fromObject = JSONObject.fromObject(tracesByJson);
				String Traces = fromObject.getString("Traces");
				boolean success = fromObject.getBoolean("Success");
				//System.err.println(">>>>>> :"+Traces.length() );
				if(success){
					if(Traces.length() > 2 ){
						hashMap.put("State", fromObject.getString("State"));
						JSONArray jsonArray = JSONArray.fromObject(Traces);
						if(jsonArray.size() >0){
							for(int i = jsonArray.size()-1; i >=jsonArray.size()-1 ; i--){        
								JSONObject object = (JSONObject)jsonArray.get(i);
								String AcceptStation = (String) object.get("AcceptStation");
								String AcceptTime = (String) object.get("AcceptTime");
								hashMap.put("AcceptStation", AcceptStation);
								hashMap.put("AcceptTime", AcceptTime);
							}
						}
						hashMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
					}else{
						hashMap.put("State", "courierError");
						hashMap.put("result", this.initResult(ResultInfo.ERROR, "courierError", "暂无物流信息！"));
					}
				}else{
					hashMap.put("State", "SuccessError");
					hashMap.put("result", this.initResult(ResultInfo.ERROR, "SuccessError", "接口返回的错误，信息返回失败/套餐用完或者未开通接口返回false！"));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				hashMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}else{
			hashMap.put("State", "waitingExpCode");
			hashMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		}
		
		return hashMap;
	}
	//获取  运单号 ，快递编码
	public Map<String, Object> getCourierNumber(String orderId){
		Map<String,Object> hashMap = new HashMap<>();
		Map<String,Object> map = new HashMap<>();
		map.put("orderId", orderId);
		map.put("state", "01");
		String code = courierService.selectCourierType(map);
		map = courierService.getOrderCourier(map);
		if(map != null){
			hashMap.put("courier_number", map.get("courier_number"));
			hashMap.put("courier_code", map.get(code+"_code"));
			hashMap.put("name", map.get("name"));
		}
		return hashMap;
	}
	
	/*
	 *物流查询 
	 */
 	@RequestMapping("/transport")
	@ResponseBody
	public ModelAndView transport(HttpServletRequest request){
 		ModelAndView mv = this.getModelAndView();
 		String orderId = request.getParameter("orderId");
  		mv.addObject("orderId",orderId);
		mv.setViewName("order/order_transport");
		return mv;
	} 

	@RequestMapping("/details")
	@ResponseBody
	public Map<String, Object> CourierDetails(HttpServletRequest request) {
		String orderId = request.getParameter("orderId");
		Map<String, Object> hashMap = getCourierNumber(orderId);
		String expNo = (String) hashMap.get("courier_number"); // 运单号
		String expCode = (String) hashMap.get("courier_code"); // 快递公司编码
		String name = (String) hashMap.get("name"); // 快递公司
		// 调用物流信息api
		Map<String, Object> map = new HashMap<>();
		Courier courier = new Courier();
		courier.setLogisticCode(expNo);
		courier.setCourierName(name);
		if(expNo!=null && expCode !=null && name !=null){
			try {
				String result = courierService.getOrderTracesByJson(expCode, expNo);
				//处理数据
				JSONObject object = JSONObject.fromObject(result);
				String state = (String) object.get("State");
				courier.setState(state);
				boolean b = object.getBoolean("Success");
				List<CourierTraces> traces = new ArrayList<>();
				if (b) {
	 				if (object.getString("Traces").length() > 2) {
						JSONArray transitListArray = object.getJSONArray("Traces");
						for (int i = transitListArray.size() - 1; i >= 0; i--) {
							JSONObject ob = (JSONObject) transitListArray.get(i);
							String acceptTime = ob.getString("AcceptTime");
							String acceptStation = ob.getString("AcceptStation");
	  						CourierTraces courierTraces = new CourierTraces();
							courierTraces.setAcceptStation(acceptStation);
							courierTraces.setAcceptTime(acceptTime);
							traces.add(courierTraces);
						}
						courier.setTracesList(traces);
						map.put("courier", courier);
						map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		 				}else{
							map.put("state", "5");
							map.put("result", this.initResult(ResultInfo.ERROR, "exception", "物流信息暂无"));
						}
					} else {	 
					   //接口返回的错误，套餐用完或者未开通接口返回false
						map.put("result", this.initResult(ResultInfo.ERROR, "exception", "物流信息暂无"));
				}
			} catch (Exception e) {
	 			e.printStackTrace();
				this.logError(logger, e.getMessage());
				map.put("result", this.initResult(ResultInfo.ERROR, "exception", "物流信息暂无"));
			}
		}else{
			map.put("courier", courier);
			map.put("state", "6");
			map.put("result", this.initResult(ResultInfo.ERROR, "waitingError", "物流信息暂无"));
		}
		return map;
	}

}
